import baseManager from "./baseManager";

const { ccclass, property } = cc._decorator;

const dotReWriteFuns = ['startInit', 'nextInit', 'getAppAssetNum'];

@ccclass
export default abstract class baseAppInit extends cc.Component {
    private appTotal = 0;
    private userTotal = 0;

    private total = 0;
    private completed = 0;

    protected appInitName: string = cc.js.getClassName(this);

    constructor() {
        super();

        if (CC_EDITOR) {
            dotReWriteFuns.forEach((funName) => {
                if (baseAppInit.prototype[funName] !== this[funName]) {
                    Editor.warn(`[${this.appInitName}] [warn] 不应该重写父类方法{${funName}}`);
                }
            });
        }
    }

    /**
     * [不可重写] 开始初始化
     */
    protected startInit() {
        baseManager.init(() => {
            // 获得app初始化所加载的资源总量
            this.appTotal = this.getAppAssetNum();
            this.userTotal = this.getUserAssetNum();

            this.completed = 0;
            this.total = this.appTotal + this.userTotal;

            this.onProgress(0, this.total);

            // 初始化app, 使用complete来实现onUserInit的切换以确保manager已完全加载
            baseManager.initManagers(() => this.nextInit(), (): any => { this.onUserInit(this.completed - this.appTotal) });
        })

    }
    /**
     * [不可重写] 初始化下一步，用户部分每完成一步需要调用一次
     */
    protected nextInit(): any {
        if (this.completed === this.total) {
            return;
        }
        this.onProgress(++this.completed, this.total);
        // 全部加载完成
        if (this.completed === this.total) {
            cc.app.emit(cc.App.EventType.EVENT_APP_INITED);
            return cc.app.manager.ui.showDefault(() => {
                // 销毁当前节点
                this.node.parent = null;
                this.node.destroy();
                // 播放默认音乐
                cc.app.manager.sound.playDefaultMusic();
            });
        }
        // 系统部分加载完毕，开始加载用户自定义
        if (this.completed > this.appTotal) {
            this.onUserInit(this.completed - this.appTotal);
        }
    }
    /**
     * [不可重写] 获得系统资源总量
     */
    protected getAppAssetNum(): number {
        return baseManager.getInitAssetNum();
    }

    /**
     * [可以重写] 默认start调用startInit，可以重写后自定义时机
     */
    protected start(): any { this.startInit(); }

    /**
     * [建议重写] 监听进度
     * @param {Number} completed
     * @param {Number} total
     */
    protected onProgress(completed: number, total: number): any { }

    /**
     * [建议重写] 监听用户初始化数据
     * @param {Number} index
     */
    protected onUserInit(index: number): any { }

    /**
     * [建议重写] 获得用户资源总量，这里返回几，就需要用户自行调用几次nextInit
     */
    protected getUserAssetNum(): number { return 0; }
}